package me.j360.springboot.simple.bean.search;

import me.j360.springboot.simple.bean.search.rule.Rule;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;

/**
 * 说明：
 * Bean类 - 查询
 *
 * ============================================================================
 * 版权所有 2015 qiushihua。
 *
 * @author qiushihua
 * @version 0.1 2015-07-22
 * ============================================================================
 * @version 0.2 2015-08-03 qiushihua 增加 返回结果 Result
 *
 */
public class Search {

    private final Page page;
    private final List<Rule> rules;
    private final Order order;

    private Search(Page page, List<Rule> rules, Order order) {
        this.page = page;
        this.rules = rules;
        this.order = order;
    }

    public Page getPage() {
        return page;
    }

    public List<Rule> getRules() {
        return rules;
    }

    public Order getOrder() {
        return order;
    }

    public static Builder newBuilder() {
        return new Builder();
    }

    public static Search simpleSearchList() {
        return newBuilder().setPage(Page.simplePage()).setOrder(Order.simpleOrder()).build();
    }

    public static Search simpleSearchUniqueResult() {
        return newBuilder().setPage(Page.uniqueResult()).setOrder(Order.simpleOrder()).build();
    }

    public static class Builder {

        private Page page;
        private List<Rule> rules;
        private Order order;

        public Builder setPage(Page page) {
            this.page = page;
            return this;
        }

        public Builder addRule(Rule rule) {
            if(null == this.rules) {
                this.rules = new ArrayList<Rule>();
            }
            this.rules.add(rule);
            return this;
        }

        public Builder addRules(List<Rule> rules) {
            if(null == this.rules) {
                this.rules = new ArrayList<Rule>();
            }
            this.rules.addAll(rules);
            return this;
        }

        public Builder setOrder(Order order) {
            this.order = order;
            return this;
        }

        public Search build() {
            Assert.notNull(page, "pager 不能为空");
            Assert.notNull(order, "order 不能为空");
            return new Search(page, rules, order);
        }

    }

}
